package org.codingq92.hand;

import java.util.concurrent.ArrayBlockingQueue;

/**
 * 生产者消费者模型 - 单次生产版本
 *
 * @author: CodingQ92
 * @date: 2025/6/4 21:25
 */
public class ProduceConsumers {

    static final int QUEUE_SIZE = 10;
    static final ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<>(QUEUE_SIZE);

    public static void main(String[] args) {
        // 启动一个消费者线程
        new Thread(new Consumer()).start();
        System.out.println("消费者开始执行>>>>> ");

        // 启动多个生产者线程，每个只生产一次
        for (int i = 0; i < 10; i++) {
            new Thread(new Producer()).start();
        }
    }

    static class Producer implements Runnable {
        @Override
        public void run() {
            try {
                int data = (int) (Math.random() * 100); // 随机生成数据
                queue.put(data);
                System.out.println("生产者生产消息成功>>>>> " + data);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt(); // 保留中断状态
                System.err.println("生产者被中断>>>>> ");
            }
        }
    }

    static class Consumer implements Runnable {
        @Override
        public void run() {
            while (true) {
                try {
                    Integer item = queue.take();
                    System.out.println("消费者消费消息成功>>>>> " + item);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    System.err.println("消费者被中断>>>>> ");
                    break;
                }
            }
        }
    }
}
